﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Table_pet
{
    public class DesktopIcon
    {
        // Windows API函数
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr FindWindow(string className, string windowText);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        // Windows Shell常量
        private const int WM_COMMAND = 0x111;
        private const int WM_SYSCOMMAND = 0x112;
        private const int SC_CLOSE = 0xF060;
        private const int SC_MINIMIZE = 0xF020;
        private const int SC_MAXIMIZE = 0xF030;
        private const int SC_RESTORE = 0xF120;
        private const int SC_ARRANGE = 0xF110;
        private const int SC_TASKLIST = 0xF130;

        // ShellWindows GUID
        private static readonly Guid CLSID_ShellWindows = new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39");

        public static void OrganizeDesktopIcons()
        {
            // 查找桌面窗口的句柄
            IntPtr progmanHandle = FindWindow("Progman", "Program Manager");

            // 发送重新排列桌面图标的消息
            PostMessage(progmanHandle, WM_SYSCOMMAND, (IntPtr)SC_TASKLIST, IntPtr.Zero);

            // 查找桌面窗口的ShellView控件句柄
            IntPtr shellViewHandle = IntPtr.Zero;
            while (shellViewHandle == IntPtr.Zero)
            {
                shellViewHandle = FindWindowEx(IntPtr.Zero, shellViewHandle, "WorkerW", null);
                IntPtr folderViewHandle = FindWindowEx(shellViewHandle, IntPtr.Zero, "SysListView32", null);
                if (folderViewHandle != IntPtr.Zero)
                {
                    shellViewHandle = folderViewHandle;
                    break;
                }
            }

            // 发送重新排列桌面图标的消息
            SendMessage(shellViewHandle, WM_COMMAND, (IntPtr)SC_ARRANGE, IntPtr.Zero);
        }
    }
}